//
//  BaseNetworkManager.m
//  BaseNetworkManager
//
//  Created by zyming on 2022/8/8.
//

#import "BaseNetworkManager.h"
#import "AFNetworking.h"

//当前版本号
#define CurrentVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
//当前系统版本
#define CurrentOsversion [UIDevice currentDevice].systemVersion
///当前bundleid
#define CurrentBundleID   [[NSBundle mainBundle] bundleIdentifier]

static AFHTTPSessionManager *manager = nil;
@implementation BaseNetworkManager

+ (id)buildManager{
    if (manager == nil) {
        @synchronized (self) {
            if (manager == nil) {
                //创建请求管理者
                manager = [AFHTTPSessionManager manager];
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                //内容类型
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
                
            }
        }
    }
    return manager;
}

//GET请求
+ (void)GetWithUrlString:(NSString *)urlString parameters:(NSDictionary *_Nullable)parameters headers:(NSDictionary *_Nullable)headers success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
//    urlString = [urlString stringByAppendingString:@"?"];
//    NSArray *allkeys = [parameters allKeys];
//    for (NSString *key in allkeys) {
//        NSString *value = [parameters objectForKey:key];
//        urlString = [urlString stringByAppendingFormat:@"&%@=%@", key, value];
//    }
//    NSLog(@"请求地址:%@",urlString);
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    
    AFHTTPSessionManager *manager = [self buildManager];
    [manager GET:urlString parameters:parameters headers:headers progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        success(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
}
///POST请求
+ (void)PostWithUrlString:(NSString *)urlString parameters:(NSDictionary *_Nullable)parameters headers:(NSDictionary *_Nullable)headers success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    
    AFHTTPSessionManager *manager = [self buildManager];
    [manager POST:urlString parameters:parameters headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@",error);
        failure(error);
    }];
    ;
}
+ (void)PostBodyThirdWithUrl:(NSString *)urlString parameters:(id _Nullable)parameters headers:(NSDictionary *_Nullable)headers success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    NSData *body = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:parameters error:nil];
    request.timeoutInterval= 15;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [request setValue:[NSString stringWithFormat:@"%@",obj] forHTTPHeaderField:[NSString stringWithFormat:@"%@",key]];
    }];
    [request setHTTPBody:body];
    
    //manager
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",nil];
    manager.responseSerializer = responseSerializer;
    
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        
        if(responseObject!=nil){
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
            success(dict);
        }
        
        if (error) {
            NSLog(@"请求失败:%@",error);
            failure(error);
        }
    }]resume];
}
//PATCH请求
+ (void)PatchWithUrlString:(NSString *)urlString parameters:(NSDictionary *_Nullable)parameters headers:(NSDictionary *_Nullable)headers success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    
    AFHTTPSessionManager *manager = [self buildManager];
    [manager PATCH:urlString parameters:parameters headers:headers success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@",error);
        failure(error);
    }];
}
//PUT请求
+ (void)PutWithUrlString:(NSString *)urlString parameters:(NSDictionary *_Nullable)parameters headers:(NSDictionary *_Nullable)headers  success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    urlString = [urlString stringByAppendingString:@"?"];
    NSArray *allkeys = [parameters allKeys];
    for (NSString *key in allkeys) {
        NSString *value = [parameters objectForKey:key];
        urlString = [urlString stringByAppendingFormat:@"&%@=%@", key, value];
    }
    NSLog(@"请求地址:%@",urlString);
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    
    AFHTTPSessionManager *manager = [self buildManager];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [manager PUT:urlString parameters:parameters headers:headers success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
}
//PUT 从body传入数据
+ (void)PutBodyWithUrl:(NSString *)urlStr body:(NSDictionary *)bodyDict headers:(NSDictionary *_Nullable)headers success:(void(^)(NSDictionary *response))success failur:(void(^)(NSError *error))failur{
    
    //配置参数
    bodyDict = [self networkingParameterWithDict:bodyDict];
    NSData *body = [NSJSONSerialization dataWithJSONObject:bodyDict options:NSJSONWritingPrettyPrinted error:nil];
    //如果不需要将通过body传 那就参数放入parameters里面
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"PUT" URLString:urlStr parameters:bodyDict error:nil];
    request.timeoutInterval= 15;
    request.HTTPMethod = @"PUT";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [headers enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [request setValue:[NSString stringWithFormat:@"%@",obj] forHTTPHeaderField:[NSString stringWithFormat:@"%@",key]];
    }];
    [request setHTTPBody:body];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = responseSerializer;
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        
        if(responseObject!=nil){
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
            success(dict);
        }
        
        if (error) {
            NSLog(@"请求失败:%@",error);
            failur(error);
        }
    }]resume];
}
//DELETE请求
+ (void)DeleteWithUrlString:(NSString *)urlString parameters:(NSDictionary *_Nullable)parameters headers:(NSDictionary *_Nullable)headers success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
    //配置参数
    headers = [self networkingHeadersWithDict:headers];
    parameters = [self networkingParameterWithDict:parameters];
    AFHTTPSessionManager *manager = [self buildManager];
    [manager DELETE:urlString parameters:parameters headers:headers success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+ (void)DownloadURL:(NSString *) downloadURL  fieldName:(NSString *)fieldName progress:(void (^)(NSProgress *downloadProgress))progress destination:(void (^)(NSURL *targetPath))destination failure:(void(^)(NSError *error))faliureError{
    
    //1.创建管理者
    AFHTTPSessionManager *manage  = [AFHTTPSessionManager manager];
    
    
    //2.下载文件
    /*
     第一个参数：请求对象
     第二个参数：下载进度
     第三个参数：block回调，需要返回一个url地址，用来告诉AFN下载文件的目标地址
     targetPath：AFN内部下载文件存储的地址，tmp文件夹下
     response：请求的响应头
     返回值：文件应该剪切到什么地方
     第四个参数：block回调，当文件下载完成之后调用
     response：响应头
     filePath：文件存储在沙盒的地址 == 第三个参数中block的返回值
     error：错误信息
     */
    
    //2.1 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: downloadURL]];
    
    NSURLSessionDownloadTask *downloadTask = [manage downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {//进度
        
        if (downloadProgress) {
            progress(downloadProgress);
        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        //拼接文件全路径
        NSString *fullpath = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fieldName]];
        NSURL *filePathUrl = [NSURL fileURLWithPath:fullpath];
        
        return filePathUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nonnull filePath, NSError * _Nonnull error) {
        
        if (error) faliureError(error);
        
        if(filePath) destination(filePath);
    }];
    
    //3.启动任务
    [downloadTask resume];
}

+ (void)UploadFieldwith_URL:(NSString *)urlString andImage:(UIImage *)image andImageName:(NSString *)imageName success:(BaseHttpSuccess)success failure:(BaseHttpFailure)failure{
    
    //1.创建会话管理者
    AFHTTPSessionManager *sharedManager = [[AFHTTPSessionManager alloc]init];
    sharedManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    sharedManager.requestSerializer.timeoutInterval = 20;
    [sharedManager POST:urlString parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImageJPEGRepresentation(image, 0);
        
        [formData appendPartWithFileData:data name:@"file" fileName:imageName mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}




#pragma mark  - 私有方法
+ (NSDictionary *)networkingHeadersWithDict:(NSDictionary *)dict{
    
    NSMutableDictionary *mutHeaders = [NSMutableDictionary dictionaryWithCapacity:1];
    [mutHeaders setObject:[self getCurrentLanguage] forKey:@"Accept-Language"];
    [mutHeaders setObject:CurrentBundleID forKey:@"appId"];
    if (dict) {
        [mutHeaders addEntriesFromDictionary:dict];
    }
    return mutHeaders.copy;
}

+ (NSDictionary *)networkingParameterWithDict:(NSDictionary *)dict{
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithCapacity:4];
    
    [dictM setValue:CurrentVersion forKey:@"version"];
    [dictM setValue:CurrentOsversion forKey:@"deviceOsversion"];
    [dictM setValue:CurrentBundleID forKey:@"appId"];
//    [dictM setValue:@([GetAccountId intValue]) forKey:@"accountId"];
//    [dictM setValue:kDeviceType forKey:@"deviceType"];
    [dictM setValue:[self getCurrentLanguage] forKey:@"Accept-Language"];
    
    if (dict) {
        [dictM addEntriesFromDictionary:dict];
    }
    
    return dictM.copy;
}


+ (NSString *)getCurrentLanguage{
    NSString *currentLanguageRegion = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] firstObject];
    if ([currentLanguageRegion hasPrefix:@"zh-Hant"]) {
        //繁体
        return  @"tw";
    }else if ([currentLanguageRegion hasPrefix:@"zh-Hans"]) {
        //简体中文
        return  @"zh";
    }else if ([currentLanguageRegion hasPrefix:@"en"]) {
        //英文
        return  @"en";
    }
    return  @"tw";
}


@end
